from flask_restful import Resource
from flask_login import login_required, LoginManager, current_user
from flask_siwadoc import SiwaDoc
import functools
import logging
from flask import request

siwa = SiwaDoc(title="管理后台", description="管理后台openapi文档", ui="redoc")


class LoginMixin:
    http_method_names = ["get", "post", "put", "delete", "patch"]

    def __init__(self):
        for method_name in self.http_method_names:
            if hasattr(self, method_name):
                method = getattr(self, method_name)
                method = login_required(method)
                setattr(self, method_name, method)


class UserAPI(Resource, LoginMixin):
    """
    子类的get、post、put、delete、patch方法均需要登录
    """
    pass

def permission(permission_en_name):
    """
    权限控制装饰器
    """

    def wrapper(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            tag = False  # 标记用户是否有这个权限
            for permission in current_user.permissions:
                if permission["en_name"] == permission_en_name:
                    tag = True
                    break
            # 超级管理员拥有所有权限
            if current_user.super_admin:
                tag = True
            if not tag:
                # p = Permission.query.filter(Permission.en_name == permission_en_name).scalar()
                # return rscode_response(RsCode.NO_PERMISSION, new_msg=f"没有[{p.cn_name}]权限")
                pass
            ret = func(*args, **kwargs)
            return ret

        return inner

    return wrapper


class RsCode:
    """
    状态码，方便直接.出来
    """
    SUCCESS = (200, "成功")
    ARGS_ERROR = (400, "参数校验失败")
    NO_PERMISSION = (401, "没有操作权限")
    NO_LOGIN = (403, "用户未登录或登录已过期")
    OTHER_ERROR = (500, "其他错误")
    SERVER_BUSY = (999, "服务器繁忙")
    TAG_IS_NOT_EXIST = (501,"tag id 不存在")
    USER_TAG_ADD_FAILED = (501, "用户标签添加失败")
    USER_ID_VERIFY_FAILED = (501, "user id 不存在")


def rscode_response(rs_code=RsCode.SUCCESS, data=None, new_msg=None):
    code, msg = rs_code

    if new_msg is not None:
        msg = new_msg

    return {"code": code, "msg": msg, "data": data}


def create_log(remark, ignore_params=False):
    """
    创建操作日志
    remark:操作备注
    """
    params = f"接口：{request.path}\n请求方式：{request.method}"
    if not ignore_params:
        params += f"\n参数：{request.data.decode()}"
    # log = Log(
    #     user_id=current_user.id,
    #     ip=request.remote_addr if request.remote_addr else "test",
    #     remark=remark,
    #     params=params,
    #     create_time=datetime.datetime.now()
    # )
    # db.session.add(log)
    # safe_commit(db)